﻿using Quartz;
using Quartz.Impl;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TaskManageDemo.Data;
using TaskManageDemo.Data.Entitys;

namespace TaskManageDemo.Core
{
    public class JobScheduler : IJobScheduler
    {
        private ISchedulerFactory _factory = null; //调度器工厂
        private IScheduler _quartzScheduler = null;//调度器

        private readonly IRepository _scheduleTask;
        public JobScheduler(IRepository scheduleTask)
        {
            this._scheduleTask = scheduleTask;
            this._factory = new StdSchedulerFactory();
            this._quartzScheduler = _factory.GetScheduler();
            this.ScheduleJob();
            Start();
        }

        /// <summary>
        /// 停止作业
        /// </summary>
        /// <param name="waitForJobsToComplete"></param>
        public void Shutdown(bool waitForJobsToComplete = true)
        {
            if (_quartzScheduler != null)
            {
                _quartzScheduler.Shutdown(waitForJobsToComplete);

            }
        }
        /// <summary>
        /// 重新开始所有的作业
        /// </summary>
        public void ResumeAll()
        {
            if (_quartzScheduler != null)
            {
                _quartzScheduler.ResumeAll();
            }
        }

        /// <summary>
        /// 启动调度器
        /// </summary>
        public void Start()
        {
            if (_quartzScheduler != null)
            {
                _quartzScheduler.Start();
            }
        }

        /// <summary>
        /// 暂停作业
        /// </summary>
        public void PauseAll()
        {
            if (_quartzScheduler != null)
            {
                _quartzScheduler.PauseAll();
            }
        }

        private void ScheduleJob()
        {
            //取出所有允许运行的作业
            //var tasks= _scheduleTask.GetAll<ScheduleTask>().ToList();
            string sql = "select * from ScheduleTask where Allowused=1";
            var tasks = _scheduleTask.Query<ScheduleTask>(sql).ToList();
            if (tasks.Count <= 0) return;
            foreach (var task in tasks)
            {
                TaskManageDemo.Utility.Common.Execute<IScheduler, ScheduleTask, Tuple<IJobDetail, ITrigger>>(JobHelp.CreatScheduleJob, _quartzScheduler, task, "创建作业失败");
            }
        }

    }
}
